from django.shortcuts import render
import json
import memcache
import requests
import time
import random
import os

from django.core.mail import send_mail
from django.contrib.auth.hashers import make_password, check_password
from django.db.models import Q
from rest_framework.response import Response
from rest_framework.views import APIView
from love.settings import EMAIL_HOST_USER
from makelove import models
from . import serializers

from love.settings import conn
from utils import get_auth_code
from utils.get_sitnature import Judge
from utils.get_user_add import get_add
from utils.User_auth import session_auth

m = memcache.Client(['47.97.218.145'])



user_on_line_list=[]

class SendEmile(APIView):
    """
    发送邮件接口，用memcached进行缓存
    """

    def post(self, request):
        data = {}
        emile = request.data.get('emile')
        code = m.get(emile)
        print(code, '5555')
        if code:
            data['message'] = '验证码已存在'
            data['code'] = 4001
            return Response(data)
        else:
            message = get_auth_code.get_code()
            send_mail(
                subject='欢迎注册有缘网',
                message='欢迎注册有缘网，您本次验证码为%s' % message,
                from_email=EMAIL_HOST_USER,
                recipient_list=[emile]
            )
            m.set(emile, message, 60)
            data['message'] = '验证码已发送,请注意查收'
            data['code'] = 0
            return Response(data)


class Verify_emile(APIView):
    def post(self, request):
        data = {}
        try:
            code = request.data.get('code')
            emile = request.data['emile']
            print(code, emile)
        except:
            data['message'] = '请输入验证码'
            data['code'] = 4010
            return Response(data)
        else:
            if not emile:
                data['message'] = '请输入邮箱'
                data['code'] = 4011
                return Response(data)
            ify_code = m.get(emile)
            print(ify_code, '333')
            if not ify_code:
                data['message'] = '验证码已过期或未发送'
                data['code'] = 4012
                return Response(data)
            if ify_code == code:
                data['message'] = '验证成功，请注册'
                data['code'] = 0
            else:
                data['message'] = '验证失败,请输入正确的验证码'
                data['code'] = 4013
            return Response(data)


judge = Judge()

class Register(APIView):
    """
    用户注册接口，包含用户昵称屏蔽
    """
    def post(self, request):
        user_data = request.data
        data = {}
        nickname = user_data['nickname']
        judge_dict = {1: '暴恐违禁', 2: '文本色情', 3: '政治敏感', 4: '恶意推广', 5: '低俗辱骂', }
        try:
            user = models.User.objects.get(nickname=user_data['nickname'])
        except:
            res = judge.text_judge(text=nickname)  # 敏感词屏蔽
            if res['result']['spam'] == 0:  # 判断是否通过审核
                user = serializers.Userserializers(data=user_data)
                if user.is_valid():
                    user.save()
                    data['message'] = '注册成功,请登录'
                    data['code'] = 0
                else:
                    data['message'] = user.errors
                    data['code'] = 4003
            else:
                for key in res['result']['reject']:
                    mes = ''
                    if key['label'] in judge_dict:
                        mes = mes.join(judge_dict[key['label']])
                        if key['hit']:
                            word = key['hit'][0]
                data['message'] = '您的昵称中包含敏感字符 '+word+' 涉及 '+mes+',请重试'
                data['code'] = 40013
        else:
            data['message'] = '昵称已被注册'
            data['code'] = 4002
            return Response(data)
        return Response(data)




class Login(APIView):
    def post(self, request):
        data = {}
        user_id = request.session.get('user_id')
        nickname = request.data.get('nickname')
        password = request.data.get('password')
        try:
            user = models.User.objects.get(nickname=nickname)
        except:
            data['message'] = '暂无此用户，请注册操作'
            data['code'] = 4006
        else:
            if check_password(password, user.password):
                request.session['user_id'] = user.id
                data['message'] = '登录成功'
                data['code'] = 0
            else:
                data['message'] = '密码错误'
                data['code'] = 4005
        return Response(data)


class Index(APIView):
    def get(self, request):
        """
        首页获取用户附近的人
        根据用户ip定位
        """
        data = {}
        user_id = request.session.get('user_id')
        print(user_id, '555')
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            ip = request.META.get('HTTP_X_FORWARDED_FOR')
        else:
            ip = request.META.get('REMOTE_ADDR')
        address_data = get_add(ip)
        address_data = json.loads(address_data)

        if address_data['status'] == '1':
            address = address_data['city']
            users = models.User.objects.filter(site__contains=address).all()
            user_data = serializers.Userserializers(instance=users, many=True)
            data['message'] = user_data.data
        if len(data['message']) == 0:
            users = models.User.objects.filter(is_vip=True).all()
            user_data = serializers.Userserializers(instance=users, many=True)
            data['message'] = user_data.data
        if len(data['message']) == 0:
            users = models.User.objects.order_by('-create_time')
            user_data = serializers.Userserializers(instance=users, many=True)
            data['message'] = user_data.data
        return Response(data)


class User_detail(APIView):
    def get(self, request):
        user_id = request.query_params.get('user_id', None)
        data = {}
        try:
            user = models.User.objects.get(pk=user_id)
        except:
            pass
        else:
            user_data = serializers.Userserializers(instance=user)
            data['message'] = user_data.data
            data['code'] = 0
        return Response(data)


class Follow(APIView):
    @session_auth
    def put(self, request):
        data = request.data.copy()
        data['user_one'] = request.session.get('user_id')
        res_data = {}
        try:
            follow = models.Relation.objects.get(
                Q(user_one_id=data['user_one'], user_two_id=data['user_two'], follow=1) | Q(
                    user_one_id=data['user_one'], user_two_id=data['user_two'], follow=3)
            )
        except:
            user_data = serializers.Followserializers(
                data=data, context={'follow': 1})
            if user_data.is_valid():
                user_data.save()
                res_data['code'] = 0
                res_data['message'] = '关注成功'
            else:
                res_data['code'] = 4012
                res_data['message'] = res_data.errors

        else:
            if follow.follow == 1:
                data['follow'] = 3
                follow_data = serializers.Followserializers(
                    instance=follow, data=data, partial=True)
                if follow_data.is_valid():
                    follow_data.save()
                    res_data['code'] = 4013
                    res_data['message'] = '成功取关'
                else:
                    res_data['code'] = 4014
                    res_data['message'] = follow_data.errors
            else:
                data['follow'] = 1
                follow_data = serializers.Followserializers(
                    instance=follow, data=data, partial=True)
                if follow_data.is_valid():
                    follow_data.save()
                    res_data['code'] = 4013
                    res_data['message'] = '重新关注'
                else:
                    res_data['code'] = 4014
                    res_data['message'] = follow_data.errors
        return Response(res_data)


class Logout(APIView):
    @session_auth
    def get(self, request):
        data = {}
        try:
            del request.session['user_id']
            # user_on_line_list.remove(request.session['user_id'])
        except:
            data['code'] = 4015
        else:
            data['code'] = 0
        return Response(data)


class Search(APIView):
    def post(self, request):
        data={}
        age__gte = request.data.get('start_age')
        age__lte = request.data.get('end_age')
        nickname__contains = request.data.get('nickname')
        gender = request.data.get('gender')
        filds = ['age__gte', 'age__lte', 'nickname__contains', 'gender']
        l = locals()  # 获取当前局部变量
        """
        动态data
        """
        query_match={key:l[key] for key in l if l[key] and key in filds}
        print(query_match)
        users = models.User.objects.filter(
            **query_match
        )
        print(users)
        if len(users)==0:  #代表没有符合用户搜索条件的
            data['code']=4017
        else:
            user_data=serializers.Userserializers(instance=users,many=True)
            data['code']=0
            data['message']=user_data.data
        return Response(data)



class My(APIView):
    def get(self,request):
        pass




class Upload(APIView):
    def post(self, request):
        data = {}
        data['code']=200
        
        chunk = request.data['chunkNumber']
        upload_file=request.data['file']
        identifier = request.data['identifier']
        file_name='%s%s' % (identifier,chunk)
        with open('static/media/'+file_name,'wb') as tem_file:
            for buf in upload_file.chunks():
                tem_file.write(buf)
        return Response(data)

class Join_file(APIView):
    def post(self,request):
        print(request.data)
        chunk=1
        with open('static/media/'+request.data['filename'],'wb') as tar_file:
            while True:
                try:
                    filename = 'static/media/'+request.data['uniquefile']+str(chunk)
                    tem_file=open(filename,'rb')
                    tar_file.write(tem_file.read())
                    tem_file.close()
                except IOError:
                    break
                chunk+=1
                os.remove(filename)
        return Response({'data':200})



